package com.liu.ourchat.customer.controller;

import com.google.gson.Gson;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
public class SendMessageController {
    @Autowired
    RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法

    @PostMapping(value = "/sendDirectMessage",produces = {"application/json;charset=UTF-8"})
    public String sendDirectMessage(String message) {
        Map<String,String> result = new HashMap<>();
        try{
            String messageId = String.valueOf(UUID.randomUUID());
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String createTime = simpleDateFormat.format(date);
            Map<String,Object> map=new HashMap<>();
            map.put("messageId",messageId);
            map.put("messageData",message);
            map.put("createTime",createTime);
            //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
            rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map);
            result.put("result","success");
        }catch (Exception e){
            e.printStackTrace();
            result.put("result","error");
        }

        return new Gson().toJson(result);
    }

}
